<script lang="ts">
import {defineComponent, reactive, ref, onMounted} from "vue";
import axios from "axios";
import {User, Edit, Delete, Search, Refresh, ArrowLeft} from '@element-plus/icons-vue';
import {ElMessageBox,ElMessage} from "element-plus";
import {Seller} from "../../types.ts";

export default defineComponent({
  name: 'AllSellers',
  computed: {
    Delete() {
      return Delete
    },
    Edit() {
      return Edit
    },
    Refresh() {
      return Refresh
    },
    Search() {
      return Search
    }
  },
  components: {
    ArrowLeft,
    User, Edit, Delete, Search, Refresh
  },
  setup() {
    const Sellers = ref<Seller[]>([]); // 指定数组元素类型
    const isEditing = ref(false);
    const currentSeller = reactive<Partial<Seller>>({}); // 使用Partial表示部分字段
    const searchInput = ref('');
    const dialogVisible = ref(false);
    const loading = ref(false);

    // 加载消费者数据
    const loadSellers = async () => {
      loading.value = true;
      try {
        const response = await axios.get<Seller[]>('/api/seller/all'); // 指定响应类型
        Sellers.value = response.data;
      } catch (error) {
        console.error('加载消费者信息失败:', error);
        ElMessage.error('加载消费者信息失败，请稍后重试。');
      } finally {
        loading.value = false;
      }
    };

    // 编辑消费者
    const editSeller = (Seller: Seller) => { // 参数类型明确
      Object.assign(currentSeller, Seller);
      dialogVisible.value = true;
    };

    // 保存消费者
    const saveSeller = async () => {
      try {
        if (currentSeller.id) {
          await axios.put<Seller>(`/api/seller/${currentSeller.id}`, currentSeller);
        } else {
          await axios.post<Seller>('/api/seller', currentSeller);
        }
        await loadSellers();
        dialogVisible.value = false;
      } catch (error) {
        console.error('保存消费者信息失败:', error);
        ElMessage.error('保存消费者信息失败，请稍后重试。');
      }
    };
    const goBack = () => {
      window.history.back();
    };
    const deleteSeller = (Seller: any) => {
      ElMessageBox.confirm(
          `确定要删除消费者 "${Seller.username}" 吗?`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        axios.delete(`/api/seller/${Seller.id}`)
            .then(() => {
              ElMessage.success('删除成功');
              loadSellers();
            })
            .catch((error) => {
              console.error('删除消费者信息失败:', error);
              ElMessage.error('删除消费者信息失败');
            });
      }).catch(() => {
        // 用户取消删除
      });
    };

    const addSeller = () => {
      currentSeller.id = 0;
      currentSeller.username = '';
      currentSeller.storeName = '';
      dialogVisible.value = true;
    };

    const searchSellers = () => {
      if (!searchInput.value) {
        loadSellers();
        return;
      }
      Sellers.value = Sellers.value.filter(Seller =>
          Seller.username.includes(searchInput.value) ||
          Seller.storeName.includes(searchInput.value));
    };
    onMounted(() => {
      loadSellers();
    });

    return {
      Sellers,
      isEditing,
      currentSeller,
      searchInput,
      dialogVisible,
      loading,
      loadSellers,
      editSeller,
      deleteSeller,
      saveSeller,
      addSeller,
      searchSellers,
      goBack
    };
  }
});
</script>

<template>
  <div class="Seller-management">
    <el-tooltip content="返回上一页" placement="top">
      <el-button
          circle
          plain
          @click="goBack"
          class="back-button"
      >
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
    </el-tooltip>
    <el-card shadow="never" class="header-card">
      <div class="header">
        <div class="title">
          <el-icon class="icon"><User /></el-icon>
          <h2>商家管理</h2>
        </div>
        <div class="actions">
          <el-input
              v-model="searchInput"
              placeholder="搜索用户名或邮箱"
              class="search-input"
              clearable
              @clear="loadSellers"
          >
            <template #append>
              <el-button :icon=Search @click="searchSellers" />
            </template>
          </el-input>
          <el-button
              type="primary"
              :icon=Refresh
              @click="loadSellers"
              :loading="loading"
          >
            刷新
          </el-button>
          <el-button
              type="success"
              @click="addSeller"
          >
            添加商家
          </el-button>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" class="table-card">
      <el-table
          :data="Sellers"
          v-loading="loading"
          stripe
          style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="storeName" label="邮箱" />
        <el-table-column prop="password" label="密码" width="180"/>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{row}">
            <el-button
                type="primary"
                size="small"
                :icon=Edit
                @click="editSeller(row)"
            />
            <el-button
                type="danger"
                size="small"
                :icon=Delete
                @click="deleteSeller(row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑/添加对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="currentSeller.id? '编辑消费者' : '添加消费者'"
        width="500px"
    >
      <el-form :model="currentSeller" label-width="80px">
        <el-form-item label="用户名" required>
          <el-input v-model="currentSeller.username" />
        </el-form-item>
        <el-form-item label="商铺名称" required>
          <el-input v-model="currentSeller.storeName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSeller">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.Seller-management {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.table-card {
  border-radius: 8px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
}

.title .icon {
  font-size: 1.8rem;
  color: var(--el-color-primary);
}

.actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  width: 250px;
}

.el-table {
  margin-top: 10px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.el-button--small {
  padding: 5px 10px;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }

  .actions {
    width: 100%;
  }

  .search-input {
    width: 100%;
  }
}
</style>